from rest_framework import status
from rest_framework.views import exception_handler
from django.db import DatabaseError
from rest_framework.response import Response


import logging

logger = logging.getLogger('django')  # django是settings配置文件里日志对象的名字


def custom_exception_handle(exc, context):
    """
    自定义异常处理
    :param exc: 本次请求发生的异常信息
    :param context: 本次请求发送异常的执行上下文{本次请求的request对象:异常发生的时间，行号等}
    :return:
    """
    response = exception_handler(exc, context)
    print(context)
    if response is None:
        """来到这里只有2种情况，要么程序不报错，要么就是报错了而django或者restframework不识别"""
        view = context.get('view')
        if isinstance(exc, DatabaseError):
            logger.error('[%s] %s' % (view, exc))
            response = Response({'message': '服务器内部错误,请联系工作人员'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

    return response

















# def exception_handler(exc, context):
#     """
#     Returns the response that should be used for any given exception.
#
#     By default we handle the REST framework `APIException`, and also
#     Django's built-in `Http404` and `PermissionDenied` exceptions.
#
#     Any unhandled exceptions may return `None`, which will cause a 500 error
#     to be raised.
#     """
#     if isinstance(exc, Http404):
#         exc = exceptions.NotFound()
#     elif isinstance(exc, PermissionDenied):
#         exc = exceptions.PermissionDenied()
#
#     if isinstance(exc, exceptions.APIException):
#         headers = {}
#         if getattr(exc, 'auth_header', None):
#             headers['WWW-Authenticate'] = exc.auth_header
#         if getattr(exc, 'wait', None):
#             headers['Retry-After'] = '%d' % exc.wait
#
#         if isinstance(exc.detail, (list, dict)):
#             data = exc.detail
#         else:
#             data = {'detail': exc.detail}
#
#         set_rollback()
#         return Response(data, status=exc.status_code, headers=headers)
#
#     return None











































